<template>
  <div class="employees-container">
    <pageTools>
      <template #left>
        <el-tag>共{{ total }}条记录</el-tag>
      </template>

      <template #right>
        <el-button v-arrowBtn="'q2'" size="mini" type="danger" @click="handleDownload">普通excel导出</el-button>
        <el-button size="mini" type="info">复杂表头excel导出</el-button>
        <el-button size="mini" type="success" @click="$router.push({path:'/improt',query:{type:'user'}})">excel导入</el-button>
        <el-button size="mini" type="primary" @click="addEmp">新增员工</el-button>
      </template>
    </pageTools>

    <!-- 表格 -->
    <el-card>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <el-table-column type="index" label="序号" width="60" />

        <el-table-column sortable prop="username" label="姓名" />
        <el-table-column label="头像" align="center">
          <template slot-scope="scoped">
            <img
              v-imgError="defaultImg"
              style="width: 40px; height: 40px"
              :src="scoped.row.staffPhoto"
              alt=""
            >
          </template>
        </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号" />
        <el-table-column sortable prop="workNumber" label="工号" />
        <el-table-column sortable label="聘用形式">
          <template slot-scope="scoped">{{ formatEmployment(scoped.row.formOfEmployment) }}</template>
        </el-table-column>
        <el-table-column sortable prop="departmentName" label="部门" />
        <el-table-column sortable prop="correctionTime" label="入职时间" />
        <!-- <el-table-column sortable prop="formOfEmployment" label="状态"> -->
        <!-- <el-table-column sortable prop="zip" label="状态">
          <template>
            <el-switch
              v-model="value"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column> -->
        <el-table-column sortable label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleClick(scope.row)"
            >查看</el-button>
            <el-button type="text" size="small">编辑</el-button>
            <el-button type="text" size="small">编辑</el-button>
            <el-button type="text" size="small">编辑</el-button>
            <el-button type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin: 20px; text-align: right">
        <el-pagination
          :current-page="currentPage4"
          :page-sizes="[5,10, 15, 20]"
          :page-size="pageObj.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="新增员工"
      :visible.sync="dialogFormVisible"
    >
      <empDia v-if="dialogFormVisible" @success="success" /></el-dialog>
  </div>
</template>

<script>
import { getEmployeeList } from '@/api/employees'
import defaultImg from '@/assets/common/bigUserHeader.png'
import EmployeeEnum from '@/constant/employees'
import empDia from './empDia.vue'
export default {
  name: 'Employees',
  components: { empDia },
  data() {
    return {
      value: true,
      defaultImg,
      tableData: [],
      pageObj: {
        page: 1,
        size: 5
      },
      total: 0,
      currentPage4: 1,
      dialogFormVisible: false,
      tHeader: []
    }
  },
  computed: {},
  created() {
    this.loadEmp()
  },
  methods: {
    // 查看详情
    handleClick(row) {
      //  实现页面跳转 =====
      /*
      声明式导航   router-link
      编程式导航   this.$router.push()
      */
      // this.$router.push('/employees/detail/'+row.id)  === path: 'detail/:id',
      //  this.$router.push('/detail/' + row.id) //  path: '/detail/:id',
      // this.$router.push({ path: '/detail/' + row.id })
      // this.$router.push({ name: 'detail', params: { id: row.id }})
      // this.$router.push({ name: 'detail', query: { id: row.id }, params: { name: 'jack' }})
      this.$router.push({ name: 'detail', params: { id: row.id }})
    },
    // 获取数据
    async loadEmp() {
      const res = await getEmployeeList(this.pageObj)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 页码
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageObj.size = val
      this.loadEmp()
    },
    // 翻页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageObj.page = val
      this.loadEmp()
    },
    // 获取 聘用形式 的函数
    formatEmployment(num) {
      if (num) {
        // eslint-disable-next-line eqeqeq
        const obj = EmployeeEnum.hireType.find(item => item.id == num)
        // console.log(num, 99888)
        // console.log(obj.value, 99888777)
        return obj.value
      } else {
        return '未知'
      }
    },
    // 新增员工
    addEmp() {
      this.dialogFormVisible = true
    },
    // 子传父
    success() {
      // 添加员工成功后
      this.dialogFormVisible = false
      // 重新刷新页面
      this.loadEmp()
    },
    // excel 导出
    async handleDownload() {
      const res = await getEmployeeList({ page: 1, size: this.total })

      // this.downloadLoading = true // 进度条开始
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date'] // 定义表头

        // 需要导出的数据
        // const list = this.tableData // 数据改成 tableData 数据
        const list = res.data.rows // 处理所有数据

        // 一定要二维数组
        const data = this.formatJson(list) // 返回值是一个二维数组
        excel.export_json_to_excel({
          // multiHeader: [], // 二维数组，设置多表头
          // merges: [], // 相当于合并单元格
          header: this.tHeader, // 表头 - 表头此时里面有值
          data, // 显示表格的数据
          filename: this.filename, // 设置导出的文件名称
          autoWidth: this.autoWidth, // 自动匹配表格宽度 布尔类型
          bookType: this.bookType // 设置导出的文件类型  文件后缀
        })
        // this.downloadLoading = false // 进度条结束
      })
    },
    // 处理为二维数组的函数
    formatJson(jsonData) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      // 给表头赋值
      this.tHeader = Object.values(map)

      // 1. 把数据的英文转成中文，
      // 2. 把 JS时间 转成 Excel时间
      return jsonData.map(item => {
        // 获取的每一项的数据有很多，我们需要做筛选
        const newObj = {} // 需要收集的字段数据
        const enKey = Object.keys(map) // 获取的是英文键[]

        enKey.forEach(key => {
          // 会循环10次 - 将 英文键中的值 赋值给 中文键
          console.log(item, key, 777)
          newObj[map[key]] = item[key] // item[key] 是 jsonData 的每条数据的属性值
        })
        console.log(newObj, 666)
        return Object.values(newObj) // Object.values(newObj) 会返回一个数组 - 接着 map return 也会返回一个数组，形成一个二维数组
      })
    }
  }
}
</script>
<style lang='scss'  scoped>
.employees-container{
  padding: 20px 30px;

}
</style>
